package com.imooc.luckmoney;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/luckymoneys")
public class LuckymoneyController {
    @Autowired
    private LuckmoneyRepository luckmoneyRepository;
    @Autowired
    private LuckymoneyService luckymoneyService;


    @GetMapping
    public List<Luckymoney> list(){
        return luckmoneyRepository.findAll();
    }

    @PostMapping
    public Luckymoney doCreate(@RequestParam("producer")String producer,
                               @RequestParam("money")BigDecimal money){
        Luckymoney luckymoney=new Luckymoney();
        luckymoney.setProducer(producer);
        luckymoney.setMoney(money);
        return luckmoneyRepository.save(luckymoney);
    }

    @GetMapping("/{id}")
    public Luckymoney doGetById(@PathVariable("id")Integer id){
        return luckmoneyRepository.findById(id).orElse(null);
    }

    @PutMapping
    public Luckymoney doUpdate(@RequestParam("id")Integer id,
                               @RequestParam("consumer")String consumer){
        Optional<Luckymoney> optionalLuckymoney=luckmoneyRepository.findById(id);
        if(optionalLuckymoney.isPresent()){
            Luckymoney luckymoney=optionalLuckymoney.get();
            luckymoney.setConsumer(consumer);
            return luckmoneyRepository.save(luckymoney);
        }
        return null;
    }

    @PostMapping("/two")
    public void doCreateTwo(){
        luckymoneyService.createTwo();
    }
}
